using UnityEngine;
using UnityEditor;
using ChosTIS;
using System.Linq;

public class GridSizeEditor : EditorWindow
{
    private GridConfigSO gridConfig;
    private float newTileSize = 20f; // 默认值
    private bool showWarning = false;
    private string warningMessage = "";

    [MenuItem("Tools/Grid Size Editor")]
    public static void ShowWindow()
    {
        GetWindow<GridSizeEditor>("Grid Size Editor");
    }

    private void OnEnable()
    {
        // 自动查找唯一GridConfigSO
        string[] guids = AssetDatabase.FindAssets("t:GridConfigSO");
        if (guids.Length > 0)
        {
            string path = AssetDatabase.GUIDToAssetPath(guids[0]);
            gridConfig = AssetDatabase.LoadAssetAtPath<GridConfigSO>(path);
            if (gridConfig != null)
                newTileSize = gridConfig.tileSizeWidth;
        }
    }

    private void OnGUI()
    {
        GUILayout.Label("网格单元格大小编辑器", EditorStyles.boldLabel);
        EditorGUILayout.Space();

        gridConfig = (GridConfigSO)EditorGUILayout.ObjectField("GridConfigSO资源", gridConfig, typeof(GridConfigSO), false);
        if (gridConfig == null)
        {
            EditorGUILayout.HelpBox("请先创建并指定一个GridConfigSO资源！", MessageType.Error);
            if (GUILayout.Button("在Assets/Resources创建GridConfigSO"))
            {
                var asset = ScriptableObject.CreateInstance<GridConfigSO>();
                AssetDatabase.CreateAsset(asset, "Assets/Resources/GridConfigSO.asset");
                AssetDatabase.SaveAssets();
                gridConfig = asset;
            }
            return;
        }

        // 显示当前大小
        EditorGUILayout.LabelField("当前单元格大小:", gridConfig.tileSizeWidth.ToString());

        // 输入新大小
        newTileSize = EditorGUILayout.FloatField("新的单元格大小:", newTileSize);

        // 验证输入
        if (newTileSize <= 0)
        {
            showWarning = true;
            warningMessage = "单元格大小必须大于0！";
        }
        else
        {
            showWarning = false;
        }

        // 显示警告
        if (showWarning)
        {
            EditorGUILayout.HelpBox(warningMessage, MessageType.Warning);
        }

        EditorGUILayout.Space();

        // 应用按钮
        GUI.enabled = !showWarning;
        if (GUILayout.Button("应用新大小并同步所有TetrisGrid"))
        {
            ApplyNewTileSize();
        }
        GUI.enabled = true;

        if (GUILayout.Button("一键批量赋值GridConfigSO到所有TetrisGrid"))
        {
            AssignGridConfigToAllTetrisGrids();
        }
    }

    private void ApplyNewTileSize()
    {
        Undo.RecordObject(gridConfig, "修改GridConfigSO");
        gridConfig.tileSizeWidth = newTileSize;
        gridConfig.tileSizeHeight = newTileSize;
        EditorUtility.SetDirty(gridConfig);
        AssetDatabase.SaveAssets();

        // 同步所有TetrisGrid的Pixels Per Unit Multiplier
        SyncAllTetrisGridPixelsPerUnit(newTileSize);

        EditorUtility.DisplayDialog(
            "修改成功",
            "GridConfigSO已更新，所有TetrisGrid的Pixels Per Unit Multiplier已同步。\n如有Prefab/场景未引用GridConfigSO，请使用一键批量赋值功能。",
            "确定"
        );
    }

    private void SyncAllTetrisGridPixelsPerUnit(float tileSize)
    {
        float multiplier = 20f / tileSize;
        // 1. 处理场景中的TetrisGrid
        var allTetrisGrids = GameObject.FindObjectsOfType<ChosTIS.TetrisItemGrid>(true);
        foreach (var grid in allTetrisGrids)
        {
            var img = grid.GetComponent<UnityEngine.UI.Image>();
            if (img != null)
            {
                Undo.RecordObject(img, "修改Pixels Per Unit Multiplier");
                img.pixelsPerUnitMultiplier = multiplier;
                EditorUtility.SetDirty(img);
            }
        }
        // 2. 处理所有Prefab
        string[] guids = AssetDatabase.FindAssets("t:Prefab");
        foreach (string guid in guids)
        {
            string path = AssetDatabase.GUIDToAssetPath(guid);
            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            if (prefab == null) continue;
            var grids = prefab.GetComponentsInChildren<ChosTIS.TetrisItemGrid>(true);
            bool changed = false;
            foreach (var grid in grids)
            {
                var img = grid.GetComponent<UnityEngine.UI.Image>();
                if (img != null && img.pixelsPerUnitMultiplier != multiplier)
                {
                    img.pixelsPerUnitMultiplier = multiplier;
                    EditorUtility.SetDirty(img);
                    changed = true;
                }
            }
            if (changed)
            {
                PrefabUtility.SavePrefabAsset(prefab);
            }
        }
    }

    private void AssignGridConfigToAllTetrisGrids()
    {
        if (gridConfig == null)
        {
            EditorUtility.DisplayDialog("错误", "请先指定GridConfigSO资源！", "确定");
            return;
        }
        // 场景
        var allTetrisGrids = GameObject.FindObjectsOfType<ChosTIS.TetrisItemGrid>(true);
        foreach (var grid in allTetrisGrids)
        {
            Undo.RecordObject(grid, "批量赋值GridConfigSO");
            grid.gridConfig = gridConfig;
            EditorUtility.SetDirty(grid);
        }
        // Prefab
        string[] guids = AssetDatabase.FindAssets("t:Prefab");
        foreach (string guid in guids)
        {
            string path = AssetDatabase.GUIDToAssetPath(guid);
            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            if (prefab == null) continue;
            var grids = prefab.GetComponentsInChildren<ChosTIS.TetrisItemGrid>(true);
            bool changed = false;
            foreach (var grid in grids)
            {
                if (grid.gridConfig != gridConfig)
                {
                    grid.gridConfig = gridConfig;
                    EditorUtility.SetDirty(grid);
                    changed = true;
                }
            }
            if (changed)
            {
                PrefabUtility.SavePrefabAsset(prefab);
            }
        }
        AssetDatabase.SaveAssets();
        EditorUtility.DisplayDialog("批量赋值完成", "所有TetrisGrid已引用指定的GridConfigSO。", "确定");
    }
} 